/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package control;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;

/**
 *
 * @author juampi
 */
public class TimeOutFilter  implements Filter{
    private String timeoutPage = "/nexus/faces/publico/login.jsp";
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) {
             HttpServletRequest httpServletRequest = (HttpServletRequest) request;
             HttpServletResponse httpServletResponse = (HttpServletResponse) response;
             // is session expire control required for this request?
             if (isSessionControlRequiredForThisResource(httpServletRequest)) {
                    // is session invalid?
                    if (isSessionInvalid(httpServletRequest)) {
                        String timeoutUrl = httpServletRequest.getContextPath();
                        System.out.println("Session is invalid! redirecting to timeoutpage : " + timeoutUrl);
                        httpServletResponse.sendRedirect(timeoutPage);
                        return;
                    }
            }
        }
    chain.doFilter(request, response);

    }

    public void destroy() {
        
    }


    private boolean isSessionControlRequiredForThisResource(HttpServletRequest httpServletRequest) {
        String requestPath = httpServletRequest.getRequestURI();
        boolean controlRequired = !StringUtils.contains(requestPath, getTimeoutPage());
        return controlRequired;

    }

    private boolean isSessionInvalid(HttpServletRequest httpServletRequest) {
        boolean sessionInValid = (httpServletRequest.getRequestedSessionId() != null)
        && !httpServletRequest.isRequestedSessionIdValid();
        return sessionInValid;
    }
    public String getTimeoutPage() {
        return timeoutPage;
    }
    public void setTimeoutPage(String timeoutPage) {
        this.timeoutPage = timeoutPage;
    }
}
